package db

import (
	"context"
	"goTong/app/pkg/code"
	code2 "goTong/gtong/code"
	"goTong/pkg/errors"

	"gorm.io/gorm"

	v1 "goTong/app/goods/srv/internal/data/v1"
	"goTong/app/goods/srv/internal/domain/do"
	metav1 "goTong/pkg/common/meta/v1"
)

type brands struct {
	db *gorm.DB
}

func newBrands(factory *mysqlFactory) *brands {
	return &brands{
		db: factory.db,
	}
}

func (b brands) List(ctx context.Context, opts metav1.ListMeta, orderby []string) (*do.BrandsDOList, error) {
	listBrand := &do.BrandsDOList{}

	brands := []do.BrandsDO{}
	dbBaner := b.db.Find(&brands)
	listBrand.TotalCount = dbBaner.RowsAffected
	for _, banner := range brands {
		listBrand.Items = append(listBrand.Items, &banner)
	}
	return listBrand, nil
}

func (b brands) Create(ctx context.Context, txn *gorm.DB, brands *do.BrandsDO) error {
	db := b.db.Create(brands)
	if db.Error != nil {
		return errors.WithCode(code2.ErrDatabase, db.Error.Error())
	}
	return nil
}

func (b brands) Update(ctx context.Context, txn *gorm.DB, brands *do.BrandsDO) error {
	db := b.db.Save(brands)
	if db.Error != nil {
		return errors.WithCode(code2.ErrDatabase, db.Error.Error())
	}
	return nil
}

func (b brands) Delete(ctx context.Context, ID uint64) error {
	return b.db.Where("id = ?", ID).Delete(&do.BannerDO{}).Error
}

func (b brands) Get(ctx context.Context, ID uint64) (*do.BrandsDO, error) {
	brand := &do.BrandsDO{}

	err := b.db.Where(ID).First(&brand).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.WithCode(code.ErrGoodsNotFound, err.Error())
		}
	}
	return brand, nil
}

var _ v1.BrandsStore = &brands{}
